# -*- coding: utf-8 -*-
import os
import socket
import time
import hashlib
import requests
import oss2
import json


# region up_down ugm
def download_ugm(ugm):
    url = "http://47.98.108.253:3008/get_data_from_ali"
    payload = "url={}".format(ugm)

    headers = {"Content-Type": "application/x-www-form-urlencoded"}
    response = requests.request("POST", url, headers=headers, data=payload)
    print(response.text)


def upload_ugm(ugm):
    url = "http://47.98.108.253:3008/put_data_to_ali"
    payload = {"putName": ugm}
    filename = os.path.basename(ugm)
    files = [("data", (filename, open(ugm, 'rb'), "application/octet-stream"))]
    headers = []
    response = requests.request("POST", url, headers=headers, data=payload, files=files)
    print(response.text)


# endregion

# 创建参数 用于STS授权
def createToken():
    appId = 'VQsqfKeSPIzdN0my'
    deviceId = socket.gethostname()
    _params = ''
    timestamp = str(int(round(time.time() * 1000)))
    # print(timestamp)
    str1 = appId + deviceId + _params + timestamp
    str2 = str1 + 'qORS*XVbQAjHryqKPve^hd^iWFx&P^cY'
    token = hashlib.md5(str2.encode('utf-8')).hexdigest()
    print(token)
    return appId, deviceId, token, timestamp


# STS临时授权
def getAccessKey(appId, deviceId, token, timestamp):
    url = "https://api.zhihuiliang.com/open/storage/aliyun/getAccessToken"
    payload = f'appId={appId}&deviceId={deviceId}&params=&token={token}&timestamp={timestamp}'
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded'
    }

    response = requests.request("POST", url, headers=headers, data=payload)
    resJson = response.json()
    if resJson['result'] == 'success':
        data = resJson['data']
        data = json.loads(data)
        accessKeyId = data['accessKeyId']
        accessKeySecret = data['accessKeySecret']
        securityToken = data['securityToken']
        return accessKeyId, accessKeySecret, securityToken
    else:
        return "error", "error"


# 创建Bucket对象，所有Object相关的接口都可以通过Bucket对象来进行
def createBucket(access_key_id, access_key_secret, security_token):
    endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'
    bucket_name = 'unre-cad'
    auth = oss2.StsAuth(access_key_id, access_key_secret, security_token)
    # 创建Bucket对象，所有Object相关的接口都可以通过Bucket对象来进行
    bucket = oss2.Bucket(auth, endpoint, bucket_name)
    return bucket


# 下载文件到 [localPath]
def downloadFile_FromAli(targetPath, localPath):
    try:
        appId, deviceId, token, timestamp = createToken()
        accessKeyId, accessKeySecret, securityToken = getAccessKey(
            appId, deviceId, token, timestamp)
        if accessKeyId != "error" and accessKeySecret != "error":
            bucket = createBucket(accessKeyId, accessKeySecret, securityToken)
            # bucket.get_object_to_file(
            #     targetPath, localPath)
            object_stream = bucket.get_object(targetPath)
            object_bytes = object_stream.read()
            object_json = object_bytes.decode('utf-8')
            # Load the JSON to a Python list & dump it back out as formatted JSON
            data = json.loads(object_json)
            with open(localPath, 'w', encoding="utf-8") as f:
                json.dump(data, f, ensure_ascii=False)
    finally:
        f.close()
        pass


# 获取MDY项目RowId
def getMDY_ProjectRowId(stageId):
    url = "https://api.mingdao.com/v2/open/worksheet/getFilterRows"

    payload = json.dumps({
        "appKey": "f48e719040f2d4f1",
        "sign": "OGIwMjE2MGIzMWViMjU4OTUzZTQ0YTUwMDM5MWI1Nzc4Y2ZmMzljYzQ3YTAwYzc2OGE1NGY3YmNkZjJkYmZkZg==",
        "worksheetId": "62f34f3f3f0b1fb9fa8559cc",
        "pageSize": 500000,
        "pageIndex": 1,
        "filters": [
            {
                "controlId": "62f34f3f3f0b1fb9fa8559e7",
                "dataType": 2,
                "spliceType": 1,
                "filterType": 2,
                "value": stageId
            }
        ],
        "notGetTotal": True,
        "useControlId": True
    })
    headers = {
        'Content-Type': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)
    resJson = response.json()
    if resJson['success']:
        if resJson['data']['rows']:
            return resJson['data']['rows'][0]['rowid']
        else:
            print("未查询到项目信息")
            return False
    else:
        print("请求失败")
        return False


# 获取项目下已有户型的oss文件路径
def getMDY_ApartmentData(projectRowId):
    url = "https://api.mingdao.com/v2/open/worksheet/getFilterRows"

    payload = json.dumps({
        "appKey": "f48e719040f2d4f1",
        "sign": "OGIwMjE2MGIzMWViMjU4OTUzZTQ0YTUwMDM5MWI1Nzc4Y2ZmMzljYzQ3YTAwYzc2OGE1NGY3YmNkZjJkYmZkZg==",
        "worksheetId": "62f34f3f3f0b1fb9fa8559c9",
        "pageSize": 500000,
        "pageIndex": 1,
        "filters": [
            {
                "controlId": "project",
                "dataType": 29,
                "spliceType": 1,
                "filterType": 24,
                "value": projectRowId
            }
        ],
        "notGetTotal": True,
        "useControlId": False
    })
    headers = {
        'Content-Type': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)

    resJson = response.json()
    if resJson['success']:
        if resJson['data']['rows']:
            ugmPathList = []
            for row in resJson['data']['rows']:
                ugmPathList.append(row['ugm_path'])
            return ugmPathList
        else:
            print("未查询到户型数据")
            return False
    else:
        print("请求失败")
        return False


# 主函数
# [stageId] 为项目分期ID
# [localDir] 为本地保存文件夹路径
def download_ApartmentData(stageId, localDir):
    try:
        projectRowId = getMDY_ProjectRowId(stageId)
        if projectRowId:
            ugmPathList = getMDY_ApartmentData(projectRowId)
            if ugmPathList:
                for ugmPath in ugmPathList:
                    fileName = ugmPath.split('ugmJson/')[1]
                    downloadFile_FromAli(ugmPath, os.path.join(localDir, fileName))
                return True
    except Exception as e:
        print(e)
        return False


if __name__ == '__main__':
    # 测试数据
    # download_ApartmentData(stageId="stage1", localDir="./")
    downloadFile_FromAli("ugmJson/ad087efd-db78-496d-af7a-c1bf1fab446a.json",
                         "ad087efd-db78-496d-af7a-c1bf1fab446a.json")
